package cn.jimmie.learn.pbc.base;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import cn.jimmie.learn.pbc.resource.Plugin;
import cn.jimmie.learn.pbc.resource.ShareInstance;
import cn.jimmie.learn.pbc.util.Utils;


/**
 * function :
 *
 * <p> Create Time:  2019年02月12日 18:01 </p>
 * <p> @author Jimmie.Qian  </p>
 */
public class BaseFragment extends Fragment {
    private int mContainerId;
    protected BaseActivity mContext;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (BaseActivity) context;
    }

    public void setContainerId(int containerId) {
        this.mContainerId = containerId;
    }

    protected void goFragment(String name, ClassLoader classLoader) {
        try {
            goFragment(classLoader.loadClass(name));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected void goFragment(Class<?> klass) {
        BaseFragment fragment = Utils.getFragment(klass);
        if (fragment == null) return;
        fragment.setContainerId(mContainerId);
        FragmentManager fm = mContext.getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(mContainerId, fragment);
        ft.commitAllowingStateLoss();
    }

    protected void goFragment(String name) {
        goFragment(name, plugin().getPluginClassLoader());
    }

    protected Plugin plugin() {
        return ShareInstance.instance().getPlugin();
    }
}
